<template>
  <div class="user-manage">
    <div class="page-header">
      <h2>用户管理</h2>
      <div class="header-controls">
        <div class="search-section">
          <input 
            type="text" 
            v-model="searchUsername" 
            @input="handleSearch" 
            placeholder="搜索用户名" 
            class="search-input"
          />
        </div>
        <div class="filter-section">
          <select v-model="filterUserType" @change="handleFilterChange" class="filter-select">
            <option value="">全部用户类型</option>
            <option v-for="type in filteredUserTypes" :key="type.id" :value="type.id">
              {{ type.type }}
            </option>
          </select>
        </div>
        <button class="add-btn" @click="showAddDialog">添加用户</button>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="user-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>用户类型</th>
            <th>邮箱</th>
<!--            <th>状态</th>-->
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in paginatedUserList" :key="user.id">
            <td>{{ user.id }}</td>
            <td>{{ user.userName }}</td>
            <td>{{ getUserTypeName(user.userType) }}</td>
            <td>{{ user.email }}</td>
<!--            <td>-->
<!--              <span :class="['status', user.status === 1 ? 'active' : 'inactive']">-->
<!--                {{ user.status === 1 ? '正常' : '禁用' }}-->
<!--              </span>-->
<!--            </td>-->
            <td>
              <button 
                class="edit-btn" 
                @click="handleEdit(user)"
                :disabled="!canEditUser(user)"
              >编辑</button>
              <button 
                class="delete-btn" 
                @click="handleDelete(user.id)"
                :disabled="!canDeleteUser(user)"
              >删除</button>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <div class="dialog" v-if="showDialog" @click.self="closeDialog">
      <div class="dialog-content">
        <h3>{{ isEdit ? '编辑用户' : '添加用户' }}</h3>
        <div class="form-group">
          <label>用户名：</label>
          <input type="text" v-model="currentUser.userName" placeholder="请输入用户名" />
        </div>
        <div class="form-group" v-if="!isEdit">
          <label>密码：</label>
          <input type="password" v-model="currentUser.password" placeholder="请输入密码" />
        </div>
        <div class="form-group">
          <label>邮箱：</label>
          <input type="email" v-model="currentUser.email" placeholder="请输入邮箱" />
        </div>
        <div class="form-group">
          <label>用户类型：</label>
          <select v-model="currentUser.userType">
            <option v-for="type in filteredUserTypes" :key="type.id" :value="type.id">
              {{ type.type }}
            </option>
          </select>
        </div>
<!--        <div class="form-group">-->
<!--          <label>状态：</label>-->
<!--          <select v-model="currentUser.status">-->
<!--            <option value="1">正常</option>-->
<!--            <option value="0">禁用</option>-->
<!--          </select>-->
<!--        </div>-->
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeDialog">取消</button>
          <button class="confirm-btn" @click="handleSave">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElPagination } from 'element-plus'

const userList = ref([])
const userTypes = ref([]) // 存储用户类型列表
const showDialog = ref(false)
const isEdit = ref(false)
const currentUser = ref({
  id: null,
  userName: '',
  password: '',
  userType: '1', // 默认为普通用户
  status: '1'
})

// 获取当前用户信息
const currentUserType = ref(parseInt(localStorage.getItem('userType') || '1'))
const isHR = computed(() => currentUserType.value === 5) // 人事部用户类型为5

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 添加筛选相关的响应式变量
const filterUserType = ref('')

// 添加搜索相关的响应式变量
const searchUsername = ref('')

// 获取用户列表
const fetchUserList = async () => {
  try {
    const userType = currentUserType.value.toString()
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      userName: searchUsername.value || undefined // 只在有值时传递
    }
    
    // 添加筛选条件
    if (filterUserType.value) {
      params.filterType = filterUserType.value
    }

    const response = await axios.get('/api/auth/queryUserList', {
      params,
      headers: {
        'User-Type': userType
      }
    })
    if (response.data.code === 200) {
      userList.value = response.data.data.list
      total.value = response.data.data.total
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUserList()
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchUserList()
}

// 获取用户类型列表
const fetchUserTypes = async () => {
  try {
    const response = await axios.get('/api/auth/queryUserTypeList')
    if (response.data.code === 200) {
      userTypes.value = response.data.data
    }
  } catch (error) {
    console.error('获取用户类型列表失败:', error)
  }
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

// 获取用户类型名称
const getUserTypeName = (typeId) => {
  const userType = userTypes.value.find(type => type.id === typeId)
  return userType ? userType.type : '未知类型'
}

// 过滤用户类型列表
const filteredUserTypes = computed(() => {
  if (!isHR.value) return userTypes.value
  // 人事部只能看到除了普通用户、管理员和超级管理员之外的用户类型
  return userTypes.value.filter(type => 
    type.id !== 1 && // 排除普通用户(1)
    type.id !== 2 && // 排除管理员(2)
    type.id !== 3    // 排除超级管理员(3)
  )
})

// 检查是否可以删除用户
const canDeleteUser = (user) => {
  if (!isHR.value) return true // 非人事部可以删除任何用户
  // 人事部不能删除管理员、超级管理员和普通用户
  return user.userType !== 1 && user.userType !== 2 && user.userType !== 3
}

// 检查是否可以编辑用户
const canEditUser = (user) => {
  if (!isHR.value) return true // 非人事部可以编辑任何用户
  // 人事部不能编辑管理员、超级管理员和普通用户
  return user.userType !== 1 && user.userType !== 2 && user.userType !== 3
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  currentUser.value = {
    id: null,
    userName: '',
    password: '',
    userType: isHR.value ? '4' : '1', // 人事部默认选择公关部门(4)，其他默认普通用户(1)
    status: '1'
  }
  showDialog.value = true
}

// 显示编辑对话框
const handleEdit = (user) => {
  if (!canEditUser(user)) {
    alert('您没有权限编辑该用户')
    return
  }
  isEdit.value = true
  currentUser.value = { ...user }
  showDialog.value = true
}

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false
  currentUser.value = {
    id: null,
    userName: '',
    password: '',
    userType: '1',
    status: '1'
  }
}

// 保存用户
const handleSave = async () => {
  try {
    // 如果是人事部，检查用户类型是否合法
    if (isHR.value) {
      const selectedType = parseInt(currentUser.value.userType)
      if (selectedType === 1 || selectedType === 2 || selectedType === 3) {
        alert('人事部不能添加普通用户、管理员或超级管理员')
        return
      }
    }
    
    const url = isEdit.value ? `/api/auth/update` : `/api/auth/addUser`
    const response = await axios[isEdit.value ? 'put' : 'post'](url, currentUser.value, {
      headers: {
        'User-Type': currentUserType.value
      }
    })
    if (response.data.code === 200) {
      alert(isEdit.value ? '更新成功' : '添加成功')
      closeDialog()
      fetchUserList()
    }
  } catch (error) {
    alert('操作失败')
    console.error('保存用户失败:', error)
  }
}

// 删除用户
const handleDelete = async (id) => {
  const user = userList.value.find(u => u.id === id)
  if (!canDeleteUser(user)) {
    alert('您没有权限删除该用户')
    return
  }
  
  if (!confirm('确定要删除这个用户吗？')) return
  try {
    const response = await axios.delete(`/api/auth/delete/${id}`, {
      headers: {
        'User-Type': currentUserType.value
      }
    })
    if (response.data.code === 200) {
      alert('删除成功')
      fetchUserList()
    }
  } catch (error) {
    alert('删除失败')
    console.error('删除用户失败:', error)
  }
}

// 处理筛选变化
const handleFilterChange = () => {
  currentPage.value = 1 // 重置页码
  fetchUserList()
}

// 处理搜索
const handleSearch = () => {
  // 使用防抖，避免频繁请求
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    currentPage.value = 1 // 重置页码
    fetchUserList()
  }, 300)
}

// 添加防抖定时器
let searchTimer = null

// 删除本地分页计算
const paginatedUserList = computed(() => userList.value)

onMounted(() => {
  fetchUserList()
  fetchUserTypes()
})
</script>

<style scoped>
.user-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-section {
  display: flex;
  align-items: center;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  width: 200px;
  height: 36px;
  font-size: 14px;
  transition: all 0.3s;
}

.search-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.search-input::placeholder {
  color: #bfbfbf;
}

.filter-section {
  display: flex;
  align-items: center;
}

.filter-select {
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  min-width: 150px;
  height: 36px;
  font-size: 14px;
}

.filter-select:focus {
  outline: none;
  border-color: #1890ff;
}

.add-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.user-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #e8e8e8;
}

th {
  background-color: #fafafa;
  font-weight: 500;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.active {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.inactive {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.edit-btn, .delete-btn {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  margin-right: 8px;
  cursor: pointer;
}

.edit-btn {
  background-color: #1890ff;
  color: white;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
}

.edit-btn:disabled,
.delete-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-content {
  background: white;
  padding: 24px;
  border-radius: 8px;
  width: 500px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.dialog-footer {
  margin-top: 24px;
  text-align: right;
}

.cancel-btn,
.confirm-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  margin-left: 8px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f4f4f5;
  color: #606266;
}

.confirm-btn {
  background-color: #1890ff;
  color: white;
}

.pagination-container {
  padding: 20px;
  display: flex;
  justify-content: center;
}
</style>
